package com.lkk.TicketFlow.common.context;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.lkk.TicketFlow.common.resp.MemberLoginResp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LoginMemberContext {
    private static final Logger LOG = LoggerFactory.getLogger(LoginMemberContext.class);

    // 使用 TransmittableThreadLocal 替代 ThreadLocal
    private static final TransmittableThreadLocal<MemberLoginResp> member = new TransmittableThreadLocal<>();

    public static MemberLoginResp getMember() {
        return member.get();
    }

    public static void setMember(MemberLoginResp member) {
        LoginMemberContext.member.set(member);
    }

    public static Long getId() {
        try {
            MemberLoginResp memberResp = member.get();
            if (memberResp == null) {
                LOG.warn("当前线程未设置登录会员信息");
                // 可以根据业务需求决定是抛出异常还是返回null
                throw new RuntimeException("未获取到登录会员信息");
            }
            return memberResp.getId();
        } catch (Exception e) {
            LOG.error("获取登录会员ID异常", e);
            throw e;
        }
    }

    /**
     * 新增：清理方法，防止内存泄漏
     * 建议在过滤器/拦截器的finally块中调用
     */
    public static void clear() {
        member.remove();
        LOG.debug("已清理线程本地登录信息");
    }

    /**
     * 新增：判断当前是否有登录信息
     */
    public static boolean isLogin() {
        return member.get() != null;
    }
}
